package org.intelli.dl.learn.order.service.impl;

import com.alibaba.csp.sentinel.annotation.SentinelResource;
import com.alibaba.csp.sentinel.slots.block.BlockException;
import lombok.extern.slf4j.Slf4j;
import org.intelli.dl.learn.model.order.Order;
import org.intelli.dl.learn.model.product.Product;
import org.intelli.dl.learn.order.feign.ProductFeignClient;
import org.intelli.dl.learn.order.service.OrderService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.cloud.client.loadbalancer.LoadBalancerClient;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import java.math.BigDecimal;
import java.util.Arrays;
import java.util.List;

/**
 * @author: Michael
 * @date: 2025/4/11
 * @desc:
 */
@Service
@Slf4j
public class OrderServiceImpl implements OrderService {

    @Autowired
    private DiscoveryClient discoveryClient;
    @Autowired
    private RestTemplate restTemplate;
    @Autowired
    private LoadBalancerClient loadBalancerClient;

    @Autowired
    private ProductFeignClient productFeignClient;

    @SentinelResource(value = "createOrder", blockHandler = "createOrderFallback")
    @Override
    public Order createOrder(Long productId, Long userId) {
        Order order = new Order();
//        Product product = getProductFromRemote(productId);
//        Product product = getProductFromRemoteWithLoadBalance(productId);
//        Product product = getProductFromRemoteWithLoadBalanceAnnotation(productId);
        Product product = getProductFromRemoteByFeign(productId);

        order.setId(1L);
        order.setTotalAmount(product.getPrice().multiply(new BigDecimal(product.getNum())));
        order.setUserId(userId);
        order.setNickName("小明");
        order.setAddress("北京");
        order.setProductList(Arrays.asList(product));

        return order;
    }

    // 兜底回调
    public Order createOrderFallback(Long productId, Long userId, BlockException e) {
        Order order = new Order();

        order.setId(0L);
        order.setTotalAmount(new BigDecimal(0));
        order.setUserId(userId);
        order.setNickName("未知用户");
        order.setAddress("异常信息" + e.getClass());
        order.setProductList(Arrays.asList(new Product()));

        return order;
    }

    public Product getProductFromRemote(Long productId) {
        // 1. 获取商品服务所在的所有机器IP+port
        List<ServiceInstance> instances = discoveryClient.getInstances("service-product");

        ServiceInstance instance = instances.get(0);
        String url = "http://" + instance.getHost() + ":" + instance.getPort() + "/getProductById/" + productId;

        // 2. 给远程发送请求
        return restTemplate.getForObject(url, Product.class);
    }

    public Product getProductFromRemoteWithLoadBalance(Long productId) {
        // 1. 获取商品服务所在的所有机器IP+port
        ServiceInstance serviceInstance = loadBalancerClient.choose("service-product");

        String url = "http://" + serviceInstance.getHost() + ":" + serviceInstance.getPort() + "/getProductById/" + productId;
        log.info("远程请求url: " + url);

        // 2. 给远程发送请求
        return restTemplate.getForObject(url, Product.class);
    }

    // 基于注解的负载均衡
    public Product getProductFromRemoteWithLoadBalanceAnnotation(Long productId) {
        String url = "http://service-product/getProductById/" + productId;
        log.info("基于注解的负载均衡，远程请求url: " + url);

        // 2. 给远程发送请求
        return restTemplate.getForObject(url, Product.class);
    }

    // 基于Feign
    public Product getProductFromRemoteByFeign(Long productId) {
        return productFeignClient.getProductById(productId);
    }
}
